from Common import *
import DB
from DictParamChecker import *

class Statistic:
    def __init__(self, logger, global_data):
        self.db = DB.DB(logger)
        self.logger = logger
        self.global_data = global_data
    
    def test(self, args):
        return makeReturn(Error.SUCCESS, {'hello':'world', 'from':'statistic'})

    def __specialInputArgsTransfer(self, args):
        '''成功返回轉換後的args，否則返回-1'''
        if 'begin_time' in args:
            args['begin_time'] = timestampFromString(args['begin_time'] + ' 00:00')
        if 'end_time' in args:
            args['end_time'] = timestampFromString(args['end_time'] + ' 23:59')
        return args

    def __getCat1Percentage(self, db_func_name, args):
        checker = DictParamChecker()
        checker.addParam('begin_time', 'str', True)
        checker.addParam('end_time', 'str', True)
        checker.addParam('currency_id', 'int', True)
        args = checker.check(args)
        if type(args) == str:
            self.logger.warning(args)
            return makeReturn(Error.ILLEGAL_ARGS)
        args = self.__specialInputArgsTransfer(args)
        ret = self.db.call(db_func_name, args)
        if ret['errno'] != Error.SUCCESS:
            return ret
        ret = ret['data']
        totalAmount = 0
        for row in ret:
            totalAmount += row['amount']
        for i in range(0, len(ret)):
            ret[i]['rate'] = ret[i]['amount'] / totalAmount * 100
        return makeReturn(Error.SUCCESS, ret)

    def getIncomeCat1Percentage(self, args):
        return self.__getCat1Percentage('getIncomeCat1Percentage', args)

    def getPaymentCat1Percentage(self, args):
        return self.__getCat1Percentage('getPaymentCat1Percentage', args)

    def getIncomeAndPaymentTendency(self, args):
        checker = DictParamChecker()
        checker.addParam('begin_time', 'str', True)
        checker.addParam('end_time', 'str', True)
        checker.addParam('currency_id', 'int', True)
        checker.addParam('time_interval', 'str', True)
        args = checker.check(args)
        if type(args) == str:
            self.logger.warning(args)
            return makeReturn(Error.ILLEGAL_ARGS, args)
        args = self.__specialInputArgsTransfer(args)
        time_interval = args['time_interval']
        time_format_str = ''
        if time_interval == 'day':
            time_format_str = '%Y-%m-%d'
        elif time_interval == 'month':
            time_format_str = '%Y-%m'
        elif time_interval == 'year':
            time_format_str = '%Y'
        else:
            return makeReturn(Error.ILLEGAL_ARGS)
        ret = self.db.call('getIncomeAndPaymentTendency', args)
        if ret['errno'] != Error.SUCCESS:
            return ret
        ret = ret['data']
        for row in ret:
            row['timeme'] = time.strftime(time_format_str, time.localtime(row['timeme']))
            row['income'] /= 100
            row['payment'] /= 100
        return makeReturn(Error.SUCCESS, ret)
        
    def getIncomeAndPayment(self, args):
        checker = DictParamChecker()
        checker.addParam('time', 'str', True)
        checker.addParam('currency_id', 'int', True)
        checker.addParam('time_interval', 'str', True)
        args = checker.check(args)
        if type(args) == str:
            self.logger.warning(args)
            return makeReturn(Error.ILLEGAL_ARGS, args)
        time_interval = args['time_interval']
        time_format_str = ''
        if time_interval == 'day':
            time_format_str = '%Y-%m-%d'
            args['time'] = timeStringToDayTimestamp(args['time'])
        elif time_interval == 'month':
            time_format_str = '%Y-%m'
            args['time'] = timeStringToMonthTimestamp(args['time'])
        elif time_interval == 'year':
            time_format_str = '%Y'
            args['time'] = timeStringToYearTimestamp(args['time'])
        else:
            return makeReturn(Error.ILLEGAL_ARGS)
        ret = self.db.call('getIncomeAndPayment', args)
        if ret['errno'] != Error.SUCCESS:
            return ret
        ret = ret['data']
        ret['timeme'] = time.strftime(time_format_str, time.localtime(ret['timeme']))
        ret['income'] /= 100
        ret['payment'] /= 100
        return makeReturn(Error.SUCCESS, ret)

    def getDefaultCurrencyIncomeAndPayment(self, args):
        '''以後應該替換成多幣種的版本'''
        ret = self.db.call('getDefaultCurrency', {})
        if ret['errno'] != Error.SUCCESS:
            return ret
        default_crc_id = ret['data']['dft_crc_id']
        args['currency_id'] = default_crc_id
        return self.getIncomeAndPayment(args)

    def getPropertyBreif(self, args):
        '''獲取各個幣種的各個賬戶的當前金額以及總合
        返回值：[{crc_id,crc_name,char,acnts:[{acnt_name,acnt_id,amount}]...]
        '''
        # 从数据库中读出各个账户的余额
        if 'show_delete' in args and args['show_delete'] == '1':
            args['show_delete'] = True
        else:
            args['show_delete'] = False
        dbData = self.db.call('getAllCurrencyAndAccountsBalance', args)
        if dbData['errno'] != Error.SUCCESS:
            return dbData
        # 按照crc聚合各个账户
        crc_dict = {}
        for row in dbData['data']:
            crc_nameme = row['crc_nameme']
            if crc_nameme not in crc_dict:
                crc_dict[crc_nameme] = { \
                    'crc_id' : row['crc_id'], \
                    'crc_nameme' : crc_nameme, \
                    'crc_unit' : row['crc_unit'], \
                    'crc_char' : row['crc_char'], \
                    'acnt_info' : []}
            crc_dict[crc_nameme]['acnt_info'].append({ \
                'acnt_id' : row['acnt_id'], \
                'acnt_nameme' : row['acnt_nameme'], \
                'acnt_typepe' : row['acnt_typepe'], \
                'acnt_showable' : row['acnt_showable'], \
                'acnt_deleteable' : row['acnt_deleteable'], \
                'acnt_balance' : row['acnt_balance']})
        # 把crc_dict变成列表
        crc_infos = []
        for key in crc_dict:
            crc_infos.append(crc_dict[key])
        # 計算各個crc的所有賬戶的資產總合，順便把金額轉換成字符串
        for crc in crc_infos:
            total = 0
            for acnt in crc['acnt_info']:
                total += acnt['acnt_balance']
                acnt['acnt_balance'] = fenIntToYuanStr(acnt['acnt_balance'])
            crc['total_balance'] = fenIntToYuanStr(total)
        
        return makeReturn(Error.SUCCESS, crc_infos)

        